package com.application.outdoor.InvoikeServices;

import it.unipr.ce.dsg.s2p.sip.Address;

import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Notification;
import android.content.Intent;
import android.util.Log;

import com.application.Activity.CommonUtilities;
import com.application.Activity.MESApplication;
import com.application.Activity.frmBieuQuyetMoiRoiNhom;
import com.application.Activity.frmChatPeerActivity;
import com.application.Activity.frmTreeNodeActivity;
import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.NotificationController;
import com.application.Controller.ReadWriteFileController;
import com.application.Network.Protocol;
import com.application.PhanQuyen.Quyen;

public class OperationsInvoike extends BaseInvoike {

	final static String TAG = Protocol.TAG;

	public OperationsInvoike() {
		super();
		url += "/OperationsServlet";
		;
	}

	// <><><><><><><><><><><><><><><>SEND
	// MESSAGE<><><><><><><><><><><><><><><><><><><><><><><>
	public void SendVoteKickMember(String userNameBeKick, String nguoiGui, int time) throws Exception {
		Log.d("Phu", "vao SendVoteKickMember");
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.KICK_MEMBER_OUT_MESSAGE));
		params.add(new BasicNameValuePair(Protocol.TIME_VOTE_KICK, time + ""));
		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, nguoiGui));
		params.add(new BasicNameValuePair(Protocol.USERNAME_BE_KICK, userNameBeKick));
		params.add(new BasicNameValuePair(Protocol.ID_NHOM, CommonUtilities.idNhomHienTai + ""));
		post(url, params);
	}

	public void SendFeedbackKickMember(String NguoiGui, String NguoiNhan, int vote) throws Exception {
		Log.d("Phu", "vao ham SendFeedbackKickMember");
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.KICK_MEMBER_OUT_FEEDBACK));
		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
		params.add(new BasicNameValuePair(Protocol.NGUOI_NHAN, NguoiNhan));
		params.add(new BasicNameValuePair(Protocol.VOTE_FEEDBACK_KICK, vote + ""));
		post(url, params);
	}

	public void SendResultVoteKickMember(String NguoiGui, int result, String userNameBeKick) throws Exception {
		Log.d("Phu", "vao ham SendResultVoteKickMember");

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.KICK_MEMBER_OUT_RESULT));
		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
		params.add(new BasicNameValuePair(Protocol.USERNAME_BE_KICK, userNameBeKick));
		params.add(new BasicNameValuePair(Protocol.VOTE_KICK_RESULT, result + ""));
		params.add(new BasicNameValuePair(Protocol.ID_NHOM, CommonUtilities.idNhomHienTai + ""));
		post(url, params);
	}

	public void SendStopTalkMember(String NguoiGui, int time, String NguoiNhan) throws Exception {
		Log.d("Phu", "vao ham SendStopTalkMember");

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.STOP_TALKING_ONE_MEMBER));
		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
		params.add(new BasicNameValuePair(Protocol.NGUOI_NHAN, NguoiNhan));
		params.add(new BasicNameValuePair(Protocol.TIME_STOP_TALK, time + ""));
		post(url, params);
	}

	// public void SendChatPeerMessage(String NguoiGui, String NguoiNhan ,
	// String NoiDung) throws Exception {
	// Log.d("Phu", "vao ham SendChatPeerMessage");
	//
	// ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
	// params.add(new BasicNameValuePair(Protocol.CMD,
	// Protocol.CHAT_PEER_MESSAGE));
	// params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
	// params.add(new BasicNameValuePair(Protocol.NGUOI_NHAN, NguoiNhan));
	// params.add(new BasicNameValuePair(Protocol.CONTENT_PEER_MESS, NoiDung));
	// post(url, params);
	// }

	public void SendAcceptTalkMember(String NguoiGui, String NguoiNhan) throws Exception {
		Log.d("Phu", "vao ham SendAcceptTalkMember");

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.ACCEPT_TALKING_ONE_MEMBER));
		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
		params.add(new BasicNameValuePair(Protocol.NGUOI_NHAN, NguoiNhan));
		post(url, params);
	}
	
	public void SendBieuQuyet(String NguoiGui, String content,int time) throws Exception {
		Log.d("Phu", "vao ham SendBieuQuyet");

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.GROUP_BIEU_QUYET));
		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
		params.add(new BasicNameValuePair(Protocol.CONTENT_TO_VOTE, content));
		
		params.add(new BasicNameValuePair(Protocol.TIME_TO_VOTE, time+""));
		params.add(new BasicNameValuePair(Protocol.ID_NHOM, CommonUtilities.idNhomHienTai + ""));
		post(url, params);
	}
	
	public void SendBieuQuyetFeedback(String NguoiGui,String NguoiNhan, String content) throws Exception {
		Log.d("Phu", "vao ham SendBieuQuyetFeedback");

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.BIEU_QUYET_FEEDBACK));
		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
		params.add(new BasicNameValuePair(Protocol.NGUOI_NHAN, NguoiNhan));
		params.add(new BasicNameValuePair(Protocol.RESULT_TO_VOTE, content));
		
		post(url, params);
	}
	
	public void SendResultBieuQuyet(String NguoiGui, int result, String content) throws Exception {
		Log.d("Phu", "vao ham SendResultBieuQuyet");

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.RESULT_BIEU_QUYET));
		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
		params.add(new BasicNameValuePair(Protocol.CONTENT_TO_VOTE, content));
		params.add(new BasicNameValuePair(Protocol.FINAL_RESULT_VOTE, result+""));
		params.add(new BasicNameValuePair(Protocol.ID_NHOM, CommonUtilities.idNhomHienTai + ""));
		post(url, params);
	}
	
	public void SendDanhGia(String NguoiGui) throws Exception {
		Log.d("Phu", "vao ham SendDanhGia");

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.GROUP_DANH_GIA));
		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
		params.add(new BasicNameValuePair(Protocol.ID_NHOM, CommonUtilities.idNhomHienTai + ""));
		post(url, params);
	}
	
	public void SendDanhGiaFeedback(String NguoiGui,String NguoiNhan,String result) throws Exception {
		Log.d("Phu", "vao ham SendDanhGiaFeedback");

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.DANH_GIA_FEEDBACK));
		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
		params.add(new BasicNameValuePair(Protocol.RESULT_TO_ESTIMATE, result));
		params.add(new BasicNameValuePair(Protocol.NGUOI_NHAN, NguoiNhan));
		post(url, params);
	}
	
	public void SendResultDanhGia(String NguoiGui,String result) throws Exception {
		Log.d("Phu", "vao ham SendResultDanhGia");

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.RESULT_DANH_GIA));
		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
		params.add(new BasicNameValuePair(Protocol.ID_NHOM, CommonUtilities.idNhomHienTai + ""));
		params.add(new BasicNameValuePair(Protocol.FINAL_RESULT_ESTIMATE, result));

		post(url, params);
	}

	public void SendChatPeerNoneRule(String NguoiGui, String NguoiNhan) throws Exception {
		Log.d("Phu", "vao ham SendChatPeerNoneRule");

		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.CHAT_FEEDBACK_NON_RULE));
		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
		params.add(new BasicNameValuePair(Protocol.NGUOI_NHAN, NguoiNhan));
		post(url, params);
	}

//	public void SendStopDiscuss(String NguoiGui) throws Exception {
//		Log.d("Phu", "vao ham SendChatPeerNoneRule");
//
//		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
//		params.add(new BasicNameValuePair(Protocol.CMD, Protocol.CLEAR_NODE_TREE));
//		params.add(new BasicNameValuePair(Protocol.NGUOI_GUI, NguoiGui));
//		params.add(new BasicNameValuePair(Protocol.ID_NHOM, CommonUtilities.idNhomHienTai + ""));
//		post(url, params);
//	}
	// <><><><><><><><><><><><><><><>RECIEVE
	// MESSAGE<><><><><><><><><><><><><><><><><><><><><><><>
	
	public  void receiveBieuQuyet(Intent intent){
		int time = Integer.parseInt(intent.getStringExtra(Protocol.TIME_TO_VOTE).trim());
		String nguoiGui = intent.getStringExtra(Protocol.NGUOI_GUI).trim();
		String s = intent.getStringExtra(Protocol.CONTENT_TO_VOTE).trim();
		final int timeVote=time;
		final String content=s;
		final String ngGui=nguoiGui;
		NetworkController.handler.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				frmTreeNodeActivity.userSenderVote=ngGui;
				ActivityController.HienThiBieuQuyetNhom(timeVote,content,new Address(""),0);
			}
		});
		Log.d("Phu", "vao ham ReceiveBieuQuyet");
	}
	
	public  void receiveDanhGia(Intent intent){
		Log.d("Phu", "vao ham ReceiveDanhGia");
		String str=intent.getStringExtra(Protocol.NGUOI_GUI).trim();
		final String nguoiGui=str;
		
		NetworkController.handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				frmTreeNodeActivity.userSenderEstimate=nguoiGui;
				ActivityController.ShowDanhGia(new Address(""));
			}
		});
		
	}
	
	public  void receiveStopDiscuss(Intent intent){
		Log.d("Phu", "vao ham receiveStopDiscuss");
		//String str=intent.getStringExtra(Protocol.NGUOI_GUI).trim();	
		NetworkController.receiveClearNode();
	}
	public  void receiveBieuQuyetResult(Intent intent){
		String content=intent.getStringExtra(Protocol.CONTENT_TO_VOTE).trim();
		int resultVote =Integer.parseInt(intent.getStringExtra(Protocol.FINAL_RESULT_VOTE).trim());
		//NetworkController.HienThiKetQuaBieuQuyet(0);
		String mess="Vấn đề: "+content+"\n Đã được quyết định : "+(resultVote==1?"Thông qua":"Bác bỏ");
		//NetworkController.HienThiKetQuaBieuQuyet(mess);
		NetworkController.ShowMessageNoticeOnTree(mess);
	}
	
	public  void receiveDanhGiaResult(Intent intent){

		String result = intent.getStringExtra(Protocol.FINAL_RESULT_ESTIMATE).trim();
		Log.i(TAG, "receive result final = "+result);
		NetworkController.HienThiKetQuaDanhGia(result);		
		//NetworkController.HienThiKetQuaDanhGia(result);
	}
	
	public  void receiveBieuQuyetFeedback(Intent intent){
		//String nguoiGui=intent.getStringExtra(Protocol.NGUOI_GUI).trim();
		//String nguoiNhan=intent.getStringExtra(Protocol.NGUOI_NHAN).trim();
		String str=intent.getStringExtra(Protocol.RESULT_TO_VOTE).trim();
		int value=Integer.parseInt(str);
		if(value==1){
			ActivityController._valueAgree+=1;
		}
		else if(value==0){
			ActivityController._valueDisAgree+=1;
		}
//		NetworkController.handler.post(new Runnable() {
//
//			@Override
//			public void run() {
//				// TODO Auto-generated method stub
//				ActivityController.CountResultBieuQuyet(0, value);
//			}
//		});
	}
	
	public  void receiveDanhGiaFeedback(Intent intent){
		//String nguoiGui=intent.getStringExtra(Protocol.NGUOI_GUI).trim();
		//String nguoiNhan=intent.getStringExtra(Protocol.NGUOI_NHAN).trim();
		String str=intent.getStringExtra(Protocol.RESULT_TO_ESTIMATE).trim();
		//final String result = str;
		Log.i(TAG, "receive result = "+str);
		String[] arrStr = str.split(";");
		String[] d = null;
		
		if(NetworkController.countEstimation==0){
			for (int i = 0; i < arrStr.length; i++) {
				ArrayList<String> arr = new ArrayList<String>();
				String s = arrStr[i];
				if (s != null && s.equals("")==false) {
					d = s.split("/");
					arr.add(d[0]);
					arr.add(d[1]);
					ActivityController.arrayEstimation.add(arr);
				}
			}
		}
		else{
		for (int i = 0; i < arrStr.length; i++) {
			//ArrayList<String> arr = new ArrayList<String>();
			String s = arrStr[i];
			if (s != null && s.equals("")==false) {
				d = s.split("/");
				Log.v("Phu", "ten at pos "+i+ActivityController.arrayEstimation.get(i).get(0));
				float curRating=Float.parseFloat(ActivityController.arrayEstimation.get(i).get(1));
				float rating=Float.parseFloat(d[1]);
				float newRating=curRating+rating;
				ActivityController.arrayEstimation.get(i).set(1, newRating+"");
				Log.v("Phu","new rating vua set="+ActivityController.arrayEstimation.get(i).get(1));
				
			}
		}
		}
		NetworkController.countEstimation+=1;
	}
	
	public  void receiveStopTalkMember(Intent intent) {
		NetworkController.SetStopDiscuss(false);
		int time = Integer.parseInt(intent.getStringExtra(Protocol.TIME_STOP_TALK).trim());
		String s = Protocol.STOP_TALKING_MESSAGE + " trong vòng " + time + " giây. Vui lòng chờ.";
		NetworkController.ShowMessageNoticeOnTree(s);
	}

	public  void receiveAcceptTalkMember(Intent intent) {
		NetworkController.SetStopDiscuss(true);
		NetworkController.ShowMessageNoticeOnTree(Protocol.ACCEPT_TALKING_MESSAGE);
	}

	public  void receiveChatPeerMess(Intent intent) {
		Log.v(TAG, "vao ham receiveChatPeerMess");
		if (NetworkController._peer.getAccount().getRuleById(Protocol.R_CHAT_RIENG) != null
				&& NetworkController._peer.getAccount().getRuleById(Protocol.R_CHAT_RIENG).getReceive()) {
			
			String nguoiGui = intent.getStringExtra(Protocol.NGUOI_GUI).trim();
			String content = intent.getStringExtra(Protocol.NOI_DUNG).trim();
			
			String idTinNhan=intent.getStringExtra(Protocol.ID).trim();
			Log.v(TAG, "nguoigui="+nguoiGui);
			Log.v(TAG, "content="+content);
			final String acc = nguoiGui;

			try {
				ReadWriteFileController.writeTXTPath(ReadWriteFileController.DIRECTORYCHATPEER + "ROLEPeer_" + acc
						+ ".txt", acc + ":" + content);
				String userNameChatting = frmChatPeerActivity._FriendChatting;
				Log.v(TAG, "user chatting="+userNameChatting);
//				if (userNameChatting == null) {
//					frmChatPeerActivity._FriendChatting = acc;
//					NetworkController.ShowChatPeer("", acc);
//				} else 
//				{
					if (userNameChatting!=null&&userNameChatting.equals(acc)) {// la dang chat voi
														// minh
						Log.d("Phu", "dang chat together");
						NetworkController.handler.post(NetworkController._runUpdateMsg);

					} else {// minh dang chat voi nguoi khac
						Log.d("Phu", "dang chat voi nguoi khac");
						// show notification co sender gui tin nhan
//						NotificationController.sendNotification(ActivityController.getPeerActivity().getBaseContext(),
//								frmChatPeerActivity.class, "Nhận tin nhắn của " + acc, content,
//								Notification.DEFAULT_SOUND, acc);
						NotificationController.sendNotification(MESApplication.getAppContext(),
								frmChatPeerActivity.class, "Tin nhắn từ " + acc, content,
								Notification.DEFAULT_SOUND, acc);
					}
//				}
				try{
					new HeThongInvoike().capNhatDaDocTinNhan(Integer.parseInt(idTinNhan));
				}catch (Exception e) {
					Log.d(TAG, "Không thể cập nhật tình trạng tin nhắn.");
				}
			} catch (Exception e) {
				Log.d(TAG, "Không thể ghi tin nhắn xuống file.");
			}
		} else {
			Log.d(TAG, "gui phan hoi ko chat");
			// NetworkController.ShowMessageNoticeTAB("Bạn không có quyền nhận tin nhắn trò chuyện.");
			try{
				String nguoiGui = intent.getStringExtra(Protocol.NGUOI_GUI).trim();
				new OperationsInvoike().SendChatPeerNoneRule(CommonUtilities.nguoiDung.getTenDangNhap(),nguoiGui );
			}
			catch (Exception e) {
				Log.d("Phu","Không thể gửi phản hồi không có quyền chat.");
			}
			NetworkController.ShowMessageNoticeOnTree("Bạn không có quyền nhận tin nhắn trò chuyện.");
		}
	}

	public  void receiveChatPeerNoneRule(Intent intent) {
		Log.v(TAG, "vao ham receiveChatPeerNoneRule");
		String ngGui=intent.getStringExtra(Protocol.NGUOI_GUI);
		NetworkController.CloseChatPeerActivity();
		NetworkController.ShowMessageNoticeOnTree(ngGui+" không có quyền nhận tin nhắn trò chuyện.");
	}

	public  void receiveFeedbackKickMember(Intent intent) {
		Log.v(TAG, "vao ham receiveFeedbackKickMember");
		int vote = Integer.parseInt(intent.getStringExtra(Protocol.VOTE_FEEDBACK_KICK).trim());

		if (vote == 1) {
			frmTreeNodeActivity.yesVote.add(1);
			Log.v("Phu", "da add yes");
		} else if (vote == 0) {
			frmTreeNodeActivity.noVote.add(1);
			Log.v("Phu", "da add no");
		}
	}

	public  void receiveResultKickMember(Intent intent) {
		Log.v(TAG, "vao ham receiveResultKickMember");
		int vote = Integer.parseInt(intent.getStringExtra(Protocol.VOTE_KICK_RESULT).trim());
		String userBeKick = intent.getStringExtra(Protocol.USERNAME_BE_KICK).trim();
		//String nguoiGui = intent.getStringExtra(Protocol.NGUOI_GUI).trim();

		String myUserName = CommonUtilities.nguoiDung.getTenDangNhap();
		if (userBeKick.equals(myUserName)) {
			Log.d("Phu", "khop userName bi kick result");
			if (vote == 1) {
				Log.d("Phu", "kq bi kick result =1 ");
				NetworkController.ShowMessageKicked();
				// xoa nguoi nay khoi danh sach nhom

			} else {
				Log.d("Phu", "kq bi kick result =0 ");
				// NetworkController.ShowMessageNotice("Mời bạn rời khỏi nhóm đã thất bại.");
				NetworkController.resetToOldRule();
				NetworkController.ShowMessageNoticeOnTree("Mời bạn rời khỏi nhóm đã thất bại.");
				// NetworkController.ShowMessageNoticeOnTree("Mời bạn rời khỏi nhóm đã thất bại.");
			}
		} else {
			Log.d("Phu", "ko khop username bi kick result");
			if (vote == 1) {
				Log.d("Phu", "kq bi kick result =1 ");
				String s = "";
				s += userBeKick + " đã bị mời ra khỏi nhóm.";
				NetworkController.ShowToastOnTree(s);
			} else {
				Log.d("Phu", "kq bi kick result =0 ");
				// NetworkController.ShowMessageNotice("Mời thành viên khỏi nhóm đã thất bại.");
				NetworkController.ShowToastOnTree("Mời thành viên khỏi nhóm đã thất bại.");
				// NetworkController.ShowMessageNoticeOnTree("Mời thành viên khỏi nhóm đã thất bại.");
			}

		}
	}

	public  void receiveVoteKickMember(Intent intent) {
		Log.v(TAG, "vao ham receiveVoteKickMember");
		int timeKick = Integer.parseInt(intent.getStringExtra(Protocol.TIME_VOTE_KICK).trim());
		String userBeKick = intent.getStringExtra(Protocol.USERNAME_BE_KICK).trim();
		String nguoiGui = intent.getStringExtra(Protocol.NGUOI_GUI).trim();
		// int idNhom =
		// Integer.parseInt(intent.getStringExtra(Protocol.ID_NHOM).trim());

		String myUserName = CommonUtilities.nguoiDung.getTenDangNhap();
		Quyen myRule = NetworkController._peer.getAccount().getRuleById(Protocol.R_NHAN_BIEU_QUYET);
		if (myRule != null && myRule.getSend()) {// co quyen bieu quyet
			if (myUserName.equals(userBeKick) == false) {
				Log.d("Phu", "ko phai nguoi bi kick trong send vote");
				frmBieuQuyetMoiRoiNhom.timeVoteKick = timeKick;
				frmBieuQuyetMoiRoiNhom.beingKickUserName = userBeKick;
				frmBieuQuyetMoiRoiNhom.userSenderKick = nguoiGui;
				NetworkController.DislayVoteKickMember();
				return;
			}
		}
		Log.d("Phu", "la nguoi bi kick");
		// NetworkController.ShowMessageNotice("Các thành viên trong nhóm đang biểu quyết để mời bạn rời khỏi nhóm.");
		NetworkController
				.ShowMessageNoticeOnTree("Các thành viên trong nhóm đang biểu quyết để mời bạn rời khỏi nhóm.");
		// NetworkController.ShowMessageNoticeOnTree("Các thành viên trong nhóm đang biểu quyết để mời bạn rời khỏi nhóm.");
		// set tat ca cac quyen cua nguoi nay la false.
		// ngưng tất cả các quyền send của người này
		NetworkController.resetAllRule(false);

	}

}
